﻿using System;
using System.IO;
using System.Reflection;

namespace Applib.Reflection
{
    public class WrapLoader : MarshalByRefObject, IDisposable
    {
        Assembly asm;
        AppDomain domain = AppDomain.CreateDomain(Guid.NewGuid().ToString());
        WrapLoader loader = null;

        public void Load(string asmFilePath)
        {
            loader = (WrapLoader)domain.CreateInstanceFromAndUnwrap(Assembly.GetExecutingAssembly().Location,
             typeof(WrapLoader).FullName);

            if (File.Exists(asmFilePath))
                asm = Assembly.LoadFile(asmFilePath);
        }


        public T RunFunction<T>(Func<Assembly, T> func) where T : class
        {
            return func(asm);
        }


        static bool HasUtf8ByteOrderMark(byte[] data)
        {
            var bom = new byte[] { 0xEF, 0xBB, 0xBF };
            return data[0] == bom[0] && data[1] == bom[1] && data[2] == bom[2];
        }


        #region IDisposable Members

        public void Dispose()
        {
            asm = null;
            AppDomain.Unload(domain);
        }

        #endregion
    }
}
